import { loginByUsername, logout } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import Cookies from 'js-cookie'
var jwtDecode = require('jwt-decode')

const user = {
  state: {
    user: '',
    status: '',
    code: '',
    token: getToken(),
    name: '',
    avatar: '',
    introduction: '',
    roles: [],
    setting: {
      articlePlatform: []
    }
  },

  mutations: {
    SET_CODE: (state, code) => {
      state.code = code
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting
    },
    SET_STATUS: (state, status) => {
      state.status = status
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_ROLES_LIST: (state, list) => {
      state.rolesList = list
    },
    SET_ROLE_NAME: (state, name) => {
      state.rolesName = name
    },
    SET_USER_ID: (state, userId) => {
      state.userId = userId
    },
    SET_ROLE_CODE: (state, code) => {
      state.rolesCode = code
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    }
  },
  actions: {
    // 用户名登录
    LoginByUsername({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        loginByUsername(username, userInfo.password).then(response => {
          const data = response.data
          commit('SET_TOKEN', data.token)
          setToken(response.data.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        const data = jwtDecode(state.token)
        const roleList = data.userRoleList
        const appRoleList = []
        for (let a = 0; a < roleList.length; a++) {
          if (roleList[a].appCode === process.env.APP_CODE) {
            appRoleList.push(roleList[a])
          }
        }
        data.userRoleList = appRoleList
        this.dispatch('_SetUserInfoState', data)
        resolve()
      })
    },

    // 获取用户权限信息
    // GetPermissions({ commit, state }) {
    //   return new Promise((resolve, reject) => {
    //     getPermissions().then(response => {
    //       const data = response.data
    //       this.dispatch('_SetPermissions', data)
    //       resolve(response)
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },

    // 同时获取用户信息和用户权限信息
    GetUserInfoAndPermission({ commit, state }) {
      return Promise.all([this.dispatch('GetUserInfo')])
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },

    // 设置用户状态
    _SetUserInfoState: function({ commit, state }, data) {
      if (data.userRoleList && data.userRoleList.length > 0) {
        commit('SET_NAME', data.realName) // 姓名
        commit('SET_AVATAR', data.avatar) // 头像
        commit('SET_ROLES', 'admin') // 用户角色
        commit('SET_ROLES_LIST', data.userRoleList) // 用户列表角色
        commit('SET_USER_ID', data.id) // 用户ID
        const rolesId = Number(Cookies.get('ROLEID'))
        const roleList = data.userRoleList
        if (roleList.length > 0) {
          if (rolesId) {
            let flag = ''
            for (var a = 0; a < roleList.length; a++) {
              if (roleList[a].id === rolesId) {
                flag = roleList[a]
                break
              }
            }
            if (flag) {
              commit('SET_ROLE_NAME', flag.name) // 用户列表角色
              commit('SET_ROLE_CODE', flag.code) // 当前用户角色Code
            } else {
              Cookies.set('ROLEID', roleList[0].id)
              commit('SET_ROLE_NAME', roleList[0].name) // 用户列表角色
              commit('SET_ROLE_CODE', roleList[0].code) // 当前用户角色Code
            }
          } else {
            Cookies.set('ROLEID', roleList[0].id)
            commit('SET_ROLE_NAME', roleList[0].name) // 用户列表角色
            commit('SET_ROLE_CODE', roleList[0].code) // 当前用户角色Code
          }
        }
      } else {
        commit('SET_TOKEN', '')
        removeToken()
      }
    }

    // 设置权限
    // _SetPermissions: function({ commit, state }, data) {
    //   commit('SET_PERMISSIONS', data)
    // }

    // 动态修改权限
    // ChangeRoles({ commit, dispatch }, role) {
    //   return new Promise(resolve => {
    //     commit('SET_TOKEN', role)
    //     setToken(role)
    //     getUserInfo(role).then(response => {
    //       const data = response.data
    //       commit('SET_ROLES', data.roles)
    //       commit('SET_NAME', data.name)
    //       commit('SET_AVATAR', data.avatar)
    //       commit('SET_INTRODUCTION', data.introduction)
    //       dispatch('GenerateRoutes', data) // 动态修改权限后 重绘侧边菜单
    //       resolve()
    //     })
    //   })
    // }
  }
}

export default user
